import { Injectable, UnauthorizedException } from "@nestjs/common";
import { UserService } from "../user/user.service";
import * as md5 from 'md5';
import { JwtService } from "@nestjs/jwt";

@Injectable()
export class AuthService {
  constructor(
    private readonly userService: UserService,
    private readonly jwtService: JwtService
  ) {}

  async login(username: string, password: string): Promise<{ token: string }> {
    const user = await this.userService.findUserByUsername(username);
    if(!user) {
      throw new UnauthorizedException('用户不存在')
    }
    const { id, username: name, password: userPassword } = user;
    const md5Password = md5(password).toUpperCase();
    if(userPassword !== md5Password) {
      throw new UnauthorizedException('密码不正确')
    }
    const payload = { id, name };
    return {
      // 将token返回给前端
      token: await this.jwtService.signAsync(payload),
    };
  }
}
